﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// Rules of CSV format:
/*
 * Quotes must be embeded.  Example: Kevin "Luis" Minehart would be: "Kevin "Luis" Minehart"
 * Whitespace is ignored
 * Fields are seperated by commas
 * new lines = new rows, unless embedded in quotation marks.
 */
namespace MySQLApplication
{
    class CSVWriter
    {
        public void write(string str_table, string str_outputFile) // Warning:  This function is not secure, at ALL.  Do not actually use this.  This is merely for example.
            // In an ideal world, this function would prevent SQL injection.  But, in this one, someone could easily abuse the "table" field and complete a query that destroys your database.
            // Friends don't let friends get SQL injected.
        {
            MySql.Data.MySqlClient.MySqlDataReader dataReader = null;
            try
            {
                string[] str_lines;


                MySQLHandler.cmd.CommandText = "SELECT * FROM " + str_table;
                dataReader = MySQLHandler.cmd.ExecuteReader();

                int lineCount = 0;

                while (dataReader.Read())
                {
                    lineCount++;
                }
                dataReader.Close();

                str_lines = new string[lineCount];
                lineCount = 0;
                dataReader = MySQLHandler.cmd.ExecuteReader();
                while (dataReader.Read())           // dataReader.read() returns a boolean that says "there is a row here to be used." as it goes down the list of rows.
                {
                    for (int i = 0; i < dataReader.FieldCount; i++) // i represents a column in array format (0 = first column, 1 = second column, etc.)
                    {
                        if (dataReader.GetValue(i).GetType() == typeof(string)) 
                           str_lines[lineCount] += "\"";

                        str_lines[lineCount] += dataReader.GetValue(i);

                        if (dataReader.GetValue(i).GetType() == typeof(string))
                            str_lines[lineCount] += "\"";

                        if(i != dataReader.FieldCount - 1)
                            str_lines[lineCount] += ",";
                    }
                    lineCount++;
                }
                System.IO.File.WriteAllLines(str_outputFile + ".csv", str_lines);
                dataReader.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                if(dataReader != null)
                    dataReader.Close();
            }
        }
    }
}
